<?php
namespace app\common\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;

class Http extends Handle
{
	public function render(Exception $e)
	{
		if (env('APP_DEBUG')){
			return parent::render($e);
		}
		// 参数验证错误
		if ($e instanceof ValidateException) {
			return $this->result($e->getError(),422);
		}
		
		// 请求异常
		if ($e instanceof HttpException && request()->isAjax()) {
			return $this->result($e->getMessage(),$e->getMessage());
		}
		
		return $this->result($e->getMessage(),422);
	}
	
	/**
	 * @Function result
	 * @param        $msg
	 * @param int    $code
	 * @param array  $data
	 * @param null   $result_code
	 * @param array  $header
	 * @param string $type
	 *
	 * @Author   tegic
	 * @Time     2018/6/1 15:59
	 */
	protected function result($msg, $code = 200, $data = [], $result_code = null, $header = [], $type = 'json')
	{
		$result_code === null && $result_code = $code;
		$result = [
			'code' => $result_code,
			'msg'  => $msg,
			'data' => $data,
		];
		$header['token'] = request()->token;
		$response = Response::create($result, $type)->code($code)->header($header);
		return $response;
	}
}